package com.zdpx.wordgen.service;

import com.zdpx.wordgen.domain.docDataFmt;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class WordService
{
    // 方法: 加载模板并填充数据
    public XWPFDocument generateWord(XWPFDocument doc, docDataFmt docData) {
        // 遍历文档中的所有段落
        Map<String,String> contentData=docData.getContent();
        for (XWPFParagraph para : doc.getParagraphs()) {
            for (String key : contentData.keySet()) {
                if (para.getText().contains(key)) {
                    List<XWPFRun> runs = para.getRuns();
                    if (runs != null) {
                        for (XWPFRun r : runs) {
                            String text = r.getText(0);
                            String des="{{" + key + "}}";
                            if (text.contains(des)) {
                                text = text.replace(des, contentData.get(key));
                                r.setText(text, 0);
                            }
                        }
                    }
                }
            }
        }

        // 遍历文档中的所有表格
        for (XWPFTable table : doc.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (String key : contentData.keySet()) {
                        String des="{{" + key + "}}";
                        if (cell.getText().contains(des)) {
                            cell.removeParagraph(0);
                            cell.setText(contentData.get(key));
                        }
                    }
                }
            }
        }
        String[][] tableData0=docData.getTable().get("table0");
        XWPFTable table=doc.getTables().get(0);
        for(String[] row:tableData0)
        {
            XWPFTableRow tableRow = table.createRow();
            for (int i = 0; i < row.length; i++) {
                XWPFTableCell cell = tableRow.getCell(i);
                cell.setText(row[i]);
            }
        }
        return doc;
    }

}